<template>
  <div id="en_table">
    <!-- v-if="tableDatas.detailTable == true" -->
    <div style="margin-bottom: 10px; width:100%" >
      <el-input v-model="search" style="width:100% !important" placeholder="快速过滤"></el-input>
    </div>
      <el-table :data="tableData" @select-all="selectAll" select-on-indeterminate @expand-change="handleDetail" @selection-change="handleSelectionChange" @row-click="rowClickHandle" @row-dblclick="detailClick" ref="topictable" 
    border stripe :max-height="tableHeight" :show-summary="summary" :summary-method="getSummaries" :span-method="objSpanMethod"
    style="width: 100%" highlight-current-row :row-class-name="tableRowClassName" :header-cell-style="{ background: '#DFF1FD', fontWeight: 900 }" :tree-props="tableDatas.treeProps" :row-key="tableDatas.rowKey" :default-expand-all="tableDatas.defaultExpandAll">
      <!-- 增加表格单选 -->
      <el-table-column v-if="tableDatas.radio" align="center" width="55" label="选择">
        <template slot-scope="scope">
          <!-- 可以手动的修改label的值，从而控制选择哪一项 仅支持查询erp-->
          <el-radio class="radio" v-model="tableDatas.templateSelection" :label="scope.row.gdno"
            >&nbsp;</el-radio>
        </template>
      </el-table-column>
      <!-- 增加表格显示详情下拉列表 -->
      <el-table-column v-if="tableDatas.detailItem" type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand" v-for="item in tableDatas.formDetail" :key="item.value">
            <el-form-item :label=item.label>
              <span>{{ props.row.detail ? props.row.detail[item.value] : "" }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <!-- 增加表格显示详情下拉嵌套表格 -->
      <el-table-column v-if="tableDatas.detailTable" type="expand">
        <template slot-scope="props">
          <en-table ref="tableQuery3" :tableDatas="props.row.detail" style="margin-left:10px;"></en-table>
          
        </template>
      </el-table-column>
      <el-table-column fixed type="index" align="center" :index="1" width="60px">
        <template #header>
          <el-popover ref='appversionId' placement="bottom" :width="260" :visible="visibless">
            <!-- 配置列面板 -->
            <transition name="fade">
              <div class="content">
                <div>选择要展示的列：</div>
                <!-- <el-checkbox-group v-model="checkedTableColumns"> -->
                <el-checkbox v-for="column in tableHead" v-model="column.show" :key="column.field" :label="column.field" show-overflow-tooltip>{{ column.name }}</el-checkbox>
                <!-- </el-checkbox-group> -->
              </div>
            </transition>
            <template slot="reference">
              <i class="el-icon-setting" style="font-size: 22px; cursor: pointer" @click="getver()"></i>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column v-if="
          tableDatas.chooseType == 'selection' ||
          tableDatas.chooseType == 'index' ||
          tableDatas.chooseType == 'expand'
        " :type="tableDatas.chooseType" width="60" align="center"></el-table-column>
      <!-- 增加多级表头 -->
      <el-table-column width="1" v-show="false"></el-table-column>
      <!-- 多级表头后续在js中修改处理数据，以下if中代码后续删除 -->
      <div v-if="tableDatas.tableCol">
        
        <div v-for="(item,index) in tableHead" :key="index">
          <el-table-column  v-if="item.child || false" :label="item.name">
            <!-- 有关于排序改动问题 -->
            <el-table-column width="1" v-show="false"></el-table-column>
            <div v-for="(item2,index2) in item.child" :key="index2" >
              <st-Head  :tableDatas="tableDatas" :item="item2"></st-Head>
            </div>
          </el-table-column>
          <st-Head v-if="!item.child" :tableDatas="tableDatas" :item="item"></st-Head> 
        </div>
      </div>
      <div v-else>
        <div v-for="(item,index) in bindTableColumns" :key="index">
          <el-table-column  v-if="item.child || false" :label="item.name">
            <div v-for="(item2,index2) in item.child" :key="index2" >
              <st-Head  :tableDatas="tableDatas" :item="item2"></st-Head>
            </div>
          </el-table-column>
          <st-Head v-if="!item.child" :tableDatas="tableDatas" :item="item"></st-Head> 
        </div>
      </div>
      <!-- 操作按钮 -->
      <el-table-column v-if="tableDatas.handleShow || false" fixed="right" align="center" label="操作" :width="tableDatas.handleWidth || 150">
        <template slot-scope="scope">
          <el-button v-if="tableDatas.editShow || false" v-has="tableDatas.editPermi || ''"  title="编辑" @click.stop="editClick(scope.row)" type="primary" size="mini">编辑</el-button>
          <!-- 新增编辑Sku -->
          <el-button v-if="tableDatas.editSku || false" v-has="tableDatas.detailPermi || ''"  title="编辑SKU" @click.stop="editSkuFun(scope.row)" type="warning" size="mini">编辑SKU</el-button>
          <el-button v-if="tableDatas.checkedShow || false" v-has="tableDatas.checkedPermi || ''"  title="生效" @click.stop="checkedClick(scope.row)" type="success" size="mini">生效
          </el-button>
          <el-button v-if="tableDatas.checkedShow2 || false" v-has="tableDatas.checkedPermi || ''"  title="修改" @click.stop="checkedClick(scope.row)" type="primary" size="mini">修改</el-button>
          <el-button v-if="tableDatas.checkedShow1 || false" v-has="tableDatas.checkedPermi || ''" @click.stop="checkedClick(scope.row)" type="primary" size="mini">修改名称</el-button>
          <el-button v-if="tableDatas.sxShow || false" v-has="tableDatas.sxPermi || ''"  title="生效" @click.stop="sxClick(scope.row)" type="primary" size="mini">生效</el-button>
          <el-button v-if="tableDatas.upShow || false" v-has="tableDatas.upPermi || ''"  title="上架" @click="upClick(scope.row)" type="success" size="mini">上架</el-button>
          <el-button v-if="tableDatas.lowShow || false" v-has="tableDatas.lowPermi || ''"  title="下架" @click.stop="lowClick(scope.row)" type="danger" size="mini">下架</el-button>
          <el-button v-if="tableDatas.subGoodsShow || false" v-has="tableDatas.subGoodsPermi || ''"  title="补货" @click="subGoodsClick(scope.row)" type="success" size="mini">补货</el-button>
          <el-button v-if="tableDatas.redGoodsShow || false" v-has="tableDatas.redGoodsPermi || ''"  title="下货" @click.stop="redGoodsClick(scope.row)" type="danger" size="mini">下货
          </el-button>
          <el-button v-if="tableDatas.detailShow || false" v-has="tableDatas.detailPermi || ''"  title="详情" @click.stop="detailClick(scope.row)" type="success" size="mini">详情</el-button>
          <!-- 新增推广 -->
          <el-button v-if="tableDatas.promotion || false" v-has="tableDatas.promotionPermi || ''"  title="推广" @click.stop="promotion(scope.row)" type="warning" size="mini">推广</el-button>
          
          <el-button v-if="tableDatas.deleteShow || false" v-has="tableDatas.deletePermi || ''"  title="删除" @click.stop="delClick(scope.row)" type="danger" size="mini">删除</el-button>
          <el-button v-if="tableDatas.deleteShow2 || false" v-has="tableDatas.delete2Permi || ''"  title="删除" @click.stop="delClick2(scope.row)" type="danger" size="mini">删除</el-button>
          
          
          <el-button v-if="tableDatas.tovoidShow || false" v-has="tableDatas.tovoidPermi || ''"  title="作废" @click.stop="tovoidClick(scope.row)" type="danger" size="mini">作废
          </el-button>
          <el-button v-if="tableDatas.tovoidShow1 || false" v-has="tableDatas.tovoidPermi || ''"  title="作废" @click.stop="tovoidClick1(scope.row)" type="danger" size="mini">作废
          </el-button>
          <el-button v-if="tableDatas.resetShow || false" v-has="tableDatas.resetPermi || ''"  title="重置密码" @click.stop="resetClick(scope.row)" type="warning" size="mini">重置密码
          </el-button>
          <el-button v-if="tableDatas.restockShow || false" v-has="tableDatas.restockPermi || ''"  title="返库" @click.stop="restockClick(scope.row)" type="warning" size="mini">返库</el-button>
          <el-button v-if="tableDatas.goBackShow || false" v-has="tableDatas.goBackPermi || ''"  title="退回" @click.stop="goBackClick(scope.row)" type="warning" size="mini">退回</el-button>
          <el-button v-if="tableDatas.goStopShow || false" v-has="tableDatas.stopPermi || ''"  title="提前终止" @click.stop="goStopClick(scope.row)" type="warning" size="mini">提前终止</el-button>

          <el-button v-if="tableDatas.sendGoodShow || false" v-has="tableDatas.sendGoodPermi || ''"  title="发货" @click.stop="sendGoodClick(scope.row)" type="warning" size="mini">发货
          </el-button>
          <el-button v-if="tableDatas.confirmShow || false" v-has="tableDatas.confirmPermi || ''"  title="确认" @click.stop="confirmClick(scope.row)" type="success" size="mini">确认
          </el-button>
          <el-button v-if="tableDatas.forbiddenShow || false" v-has="tableDatas.forbiddenPermi || ''"  :title="scope.row.stat == 1 ? '禁用' : '启用'" @click.stop="forbiddenClick(scope.row)" :type="scope.row.stat == 1 ? 'warning' : 'success'" size="mini">{{scope.row.stat == 1 ? '启用' : '禁用' }}
          </el-button>
          <el-button v-if="tableDatas.forbiddenShow1 || false" v-has="tableDatas.forbiddenPermi || ''" style="font-size: 12px"  :title="'禁用'" :type="'warning'" size="mini" @click.stop="forbiddenClick1(scope.row)"></el-button>

          <el-button v-if="tableDatas.definedShow || false" v-has="tableDatas.defined.permi || ''" style="font-size: 12px"  :title="tableDatas.defined.title" :type="tableDatas.defined.type || 'success'" size="mini" @click.stop="definedClick(scope.row)">{{tableDatas.defined.title}}</el-button>
          <el-button v-if="tableDatas.defined2Show || false" v-has="tableDatas.defined2.permi || ''" style="font-size: 12px"  :title="tableDatas.defined2.title" :type="tableDatas.defined2.type || 'success'" size="mini" @click.stop="defined2Click(scope.row)">{{tableDatas.defined2.title}}
          </el-button>
          <el-button v-if="tableDatas.defined3Show || false" v-has="tableDatas.defined3.permi || ''" style="font-size: 12px"  :title="tableDatas.defined3.title" :type="tableDatas.defined3.type || 'success'" size="mini" @click.stop="defined3Click(scope.row)">{{tableDatas.defined3.title}}
          </el-button>
          <el-button v-if="tableDatas.defined5Show || false" v-has="tableDatas.defined5.permi || ''" style="font-size: 12px"  :title="tableDatas.defined5.title" :type="tableDatas.defined5.type || 'success'" size="mini" @click.stop="defined5Click(scope.row)">{{tableDatas.defined5.title}}
          </el-button>
          <el-button v-if="tableDatas.defined4Show || false" v-has="tableDatas.defined4.permi || ''" style="font-size: 12px"  :title="tableDatas.defined4.title" :type="tableDatas.defined4.type || 'success'" size="mini" @click.stop="defined4Click(scope.row)">{{tableDatas.defined4.title}}
          </el-button>
          <span v-for="(item, index) in tableDatas.defindList" :key="index" style="padding-left: 10px">
            <el-button v-if="item.defined2Show || false" v-has="item.permi || ''" style="font-size: 12px"  :title="item.title" :type="item.type || 'success'" size="mini" @click.stop="item.defindclick(scope.row)">{{item.title}}</el-button>
          </span>
        </template>
      </el-table-column>
      <!-- <st-Head v-if="tableDatas.tableCol != true"  :tableDatas="tableDatas" :tableHead="tableHead"
        @editClick="editClick" @upClick="upClick" @subGoodsClick="subGoodsClick" @redGoodsClick="redGoodsClick" @detailClick="detailClick"
        @delClick="delClick" @delClick2="delClick2" @checkedClick="checkedClick" @tovoidClick="tovoidClick" @tovoidClick1="tovoidClick1" 
        @resetClick="resetClick" @restockClick="restockClick" @goBackClick="goBackClick" @goStopClick="goStopClick" @sendGoodClick="sendGoodClick"
        @confirmClick="confirmClick" @forbiddenClick="forbiddenClick" @forbiddenClick1="forbiddenClick1" @definedClick="definedClick"
        @defined2Click="defined2Click" @defined3Click="defined3Click"></st-Head>  -->
    </el-table>

    <el-row type="flex" justify="start" class="fyfool" v-if="moneyShow && tableDatas.footerShow">
      <p style="font-size: 14px;margin-top: 10px;margin-left:16px">
        {{tableDatas.footerName?tableDatas.footerName:'总计'}}：{{totalCostMoney.toFixed(2)}}
      </p>
    </el-row>

    <el-row v-if="pagingShow" type="flex" justify="end" class="fyfool">
      <el-popover placement="top" width="500" v-model="visible">
        <el-form inline>
          <el-form-item>
            <el-select v-model="num" placeholder="数据条数" filterable>
              <el-option v-for="(item, index) in exportNum" :key="index" :label="item.value" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="exportExecl(num)" size="small">导出</el-button>
          </el-form-item>
        </el-form>

        <el-progress :percentage="percentage" :format="format" :color="customColors" :text-inside="true" :stroke-width="26"></el-progress>
        <el-button v-if="exportSign" size="mini" slot="reference" @click="tableExport" style="margin-top: 12px">导 出</el-button>
      </el-popover>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="handleCurrentChange" @next-click="handleCurrentChange" :current-page="pageNum" :page-sizes="[15, 50, 100, 200, 500, 1000, 2000,5000]" :page-size="maxResult" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import stHead from "@/components/tableHead.vue";
import http from '../utils/http'
export default {
  name: "enTable",
  components: {
    stHead
  },
  data() {
    return {
      visibless: false,
      // loadingTable: false,
      tableHeight: "100%",
      chooseType: "", //列类型 selection多选/index显示索引/expand可展开按钮
      multipleSelection: [], //多选
      tableHead: [], //表头
      tableData: [], //表数据
      constTableData: [], //缓存表
      summary: false, //是否显示合计
      handleShow: false, //操作列显示
      pagingShow: true, //分页显示
      startPosition: 0, //开始条数
      pageNum: 1, //开始页
      maxResult: 15, //每页显示数量
      total: 0, //总数
      dcm: 2, //小数位
      search: "", //全局模糊搜索
      visible: false,
      isAllSelect: false,
      totalCostMoney: 0, //总计
      moneyShow: false, //是否显示总计金额
      exportSign: true,//表格底部是否显示导出按钮
      exportNum: [
        { value: 50 },
        { value: 100 },
        { value: 200 },
        { value: 500 },
        { value: 1000 },
        { value: 1500 },
        { value: 2000 },
        { value: 5000 },
        { value: 10000 },
        { value: 20000 },
        { value: 50000 },
        // { value: 60000 },
        // { value: 70000 },
        // { value: 100000 },
      ], //导出条数选择
      num: 50,
      percentage: 0,
      customColors: [
        { color: "#70d7eb", percentage: 1 },
        { color: "#49e5da", percentage: 50 },
        { color: "#39e3ab", percentage: 60 },
        { color: "#1cc252", percentage: 100 },
      ],
      arrs:[],//存放的是否需要合计的表头数据
      param:"", //合计时拿到的展示的表头和数据
      vueDetail:{},
      rowSpanArr: [],//存放合并行指针
      position:"0",
    };
  },
  props: ["tableDatas"],
  mounted() {
    this.$http = http
    this.getTable();
    this.getHead();
  },
  mounted() {
    this.tableHeight =
      window.innerHeight - this.$refs.topictable.$el.offsetTop - 60;
    window.addEventListener("resize", () => {
      this.tableHeight =
        window.innerHeight - this.$refs.topictable.$el.offsetTop - 60;
    });
  },
  computed: {
    bindTableColumns() {
      return this.tableHead.filter((column) => column.show);
    },
    /* 这里使用了getter和setter，这样写的好处不用自己手动监听复选框的选中事件 */
    checkedTableColumns: {
      get() {
        // 返回选中的列名
        return this.tableHead.map(column => column.filed);
      },
      set(checked) {
        // 设置表格列的显示与隐藏
        this.tableHead.forEach((column, index) => {
          // 如果选中，则设置列显示
          if (checked.includes(column.filed)) {
            column.hideTag = "1";
            column.show = true;
          } else {
            // 如果未选中，则设置列隐藏
            column.hideTag = "0";
            column.show = false;

          }
        })
      }
    }
  },
  methods: {
    getColTableColumns(){
      const gctc = (array)=>{
        const result =[]
        for (let index = 1; index < array.length; index++) {
          for (let i = 0; i < this.tableHead.length; i++) {
            if(array[index] == this.tableHead[i].field){
              result.push(this.tableHead[i])
              this.tableHead.splice(i,1)
              continue
            }
          }
        }
        return result;
      }
      this.tableDatas.tableColData.map((item)=>{
        if(Array.isArray(item)){
          const obj = {name:item[0],child:[]}
          obj.child = gctc(item)
          this.tableHead.push(obj)
        }
      })
    },
    // 获取合并的数组
    getRowSpan() {
      const Fn = ()=>{
        this.rowSpanArr = [];
        this.tableData.forEach((item, index) => {
          if (index == 0) {
            this.rowSpanArr.push(1);
            this.position = 0;
          } else {
            for (const key in this.tableData[index]) {
              if (this.tableDatas.spanMethod[key] && key == this.tableDatas.spanMethod[key]) {
                if(this.tableData[index][key] == this.tableData[index - 1][key]){
                  this.rowSpanArr[this.position] += 1; //项目名称相同，合并到同一个数组中
                  this.rowSpanArr.push(0);
                  this.tableData[index][key] = this.tableData[index - 1][key];
                }else {
                  this.rowSpanArr.push(1);
                  this.position = index;
                }
              } 
            }
          }
        });
      }
      this.$emit("suTotal", {tableData:this.tableData,callBack:Fn});
      
    },
    objSpanMethod({ row, column, rowIndex }) {
      // 只合并区域位置
      if (this.tableDatas.spanMethod && column.property != undefined && column.property == this.tableDatas.spanMethod[column.property]) {
        const _row = this.rowSpanArr[rowIndex];
        return {
          rowspan: _row, //行
          colspan: _row>0 ? 1 : 0 //列
        };
      }
    },
    getver() {
      this.visibless = !this.visibless
    },
    tableExport() {
      this.percentage = 0;
    },
    format(percentage) {
      if (percentage == 1) {
        return "正在请求数据";
      } else if (percentage == 50) {
        return "正在转换格式";
      } else if (percentage == 60) {
        return "正在写入execl";
      } else if (percentage == 100) {
        return "完成";
      }
    },
    async exportExecl(num) {
      let dataList = [];
      let params = JSON.parse(JSON.stringify(this.tableDatas.body.params));
      params.startPosition = 0;
      params.maxResult = num;
      this.percentage = 1; //正在请求数据
      let bool = await this.$http
        .GET(this.tableDatas.body.url, params)
        .then((row) => {
          if (row.code != 200 || row.data.total == 0) {
            this.$message({
              type: "warning",
              message: "导出数据为空!",
            });
            return false;
          }
          this.percentage = 50; //正在转换格式
          let excelDate = ""
          let excelDateInfo = ""
          if(row.data.page && row.data.page.rows){
            excelDate = row.data.page.rows
          }else{
            excelDate = row.data.rows
          }
          excelDate.map((item) => {
            let obj = {};
            for (let index = 0; index < this.tableHead.length; index++) {
              for (let label in item) {
                if (
                  this.tableHead[index].field == label &&
                  this.tableHead[index].format
                ) {
                  //判断format里是否包含html标签，如果有标签只提取innerText
                  // && this.tableHead[index].type == 'html' 
                  //indexOf报错时 解决方法 修改函数 查看配置时的函数 添加 else {return ""}
                  if (
                    item[label]  && this.tableHead[index].type == 'html' &&
                    this.tableHead[index].format
                      .function(item[label])
                      .indexOf("/") != -1
                  ) {
                    obj[this.tableHead[index].field] = this.tableHead[
                      index
                    ].format
                      .function(item[label])
                      .replace(/<[^<>]+?>/g, "");
                  } else {
                    // 判断券号 导出的券号应该是全券号
                    if (this.tableHead[index].field == 'ticketNo') {
                      obj[this.tableHead[index].field] = item[label];
                    } else {
                      obj[this.tableHead[index].field] = this.tableHead[
                        index
                      ].format.function(item[label]);
                    }
                  }
                } else if (
                  this.tableHead[index].field == label &&
                  !this.tableHead[index].format
                ) {
                  obj[this.tableHead[index].field] = item[label];
                }
              }
            }
            dataList.push(obj);
          });
          // if(this.param){
          //   this.param.data = dataList
          // }
          // dataList=row.data.rows
          return true;
        });
      if (!bool) {
        return;
      }
      this.percentage = 60; //正在写入execl
      let Header = [];
      let filter = [];
      let title =
        this.$route.meta.text +
        "__" +
        this.$api.dateFormat(new Date(), "yyyy-MM-dd hh：mm：ss");
      this.tableHead.map((item) => {
        Header.push(item.name);
      });
      this.tableHead.map((item) => {
        filter.push(item.field);
      });
      require.ensure([], () => {
        const {
          export_json_to_excel,
        } = require("@/components/Excel/Export2Excel");
        const tHeader = Header; // 导出的表头名
        const filterVal = filter; // 导出的表头字段名
        const list = dataList;
        const data = list.map((v) => filterVal.map((j) => v[j]));
        //push 合计 删除第一列的序号空值 
        let endSum = [];
        if(this.param){
          for(let i=0;i<this.$api.summaries(this.param,this.arrs).length; i++){
            this.param.data = dataList
            if(this.tableDatas.chooseType == 'selection' ||
            this.tableDatas.chooseType == 'index' ||
            this.tableDatas.chooseType == 'expand'){
              if(i!=1 && i!==2){
                endSum.push(this.$api.summaries(this.param,this.arrs)[i])
              }
            }else{
              if(i!=1){
                endSum.push(this.$api.summaries(this.param,this.arrs)[i])
              }
            }
          }
        }
        // console.log(this.$api.summaries(this.param,this.arrs))
        data.push(endSum)
        // console.log(data,"data",endSum)
        
        export_json_to_excel(tHeader, data, title);
      });
      this.percentage = 100; //完成
   
    },
    totalFixed(value) {
      if (value == null) {
        return null;
      }
      return this.$api.moneyFormat(value);
    },
    numFixed(value) {
      if (value == null) {
        return null;
      }
      return value.toFixed(3);
    },
    qtyFixed(value) {
      if (value == null) {
        return null;
      }
      return value.toFixed(this.dcm);
    },
    handleSelectionChange(val) {
      //表格多选
      this.$emit("selectedArr", val);
    },
    handleDetail(val,val2){
      //展开按钮点击
      this.$emit("handleDetail", {val,val2});
    },
    selectAll(val, first) {
      if (!first) {
        this.isAllSelect = !this.isAllSelect;
      }
      this.$emit("selectedArrAll", this.isAllSelect);
    },
    clearSelection() {
      this.$refs["topictable"].clearSelection(); // 取消表格多选
    },
    tableRowClassName({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex;
      let index = rowIndex + 1;
      if (index % 2 == 0) {
        return "warning-row";
      } else {
        return "warning-rows";
      }
    },
    rowClickHandle(row) {
      //单击行
      this.$emit("rowClick", row);
    },
    handleSizeChange(val) {
      //每页显示个数变化
      this.maxResult = val;
      this.getTable();
    },
    handleCurrentChange(val) {
      //当前页数
      this.pageNum = val;
      this.startPosition = (val - 1) * this.maxResult;
      this.$emit("params", {
        startPosition: this.startPosition,
        maxResult: this.maxResult,
      });
      this.getTable();
    },
    getSummaries(param) {
      var arrs = [];
      this.param = JSON.parse(JSON.stringify(param))
      for (let index = 0; index < this.tableHead.length; index++) {
        if (
          this.tableHead[index].type == "money" &&
          this.tableHead[index].sumTag != "0"
        ) {
          arrs.push({
            name: this.tableHead[index].field,
            format: true,
          });
        }
        if (
          this.tableHead[index].type != "money" &&
          this.tableHead[index].sumTag != "0"
        ) {
          arrs.push({
            name: this.tableHead[index].field,
            format: false,
          });
        }
      }
      this.arrs = JSON.parse(JSON.stringify(arrs))
      this.$emit("sumArr", this.$api.summaries(param, arrs))
      return this.$api.summaries(param, arrs);
    },
    getField(row, field) {
      //带点字段处理 如 application.id
      if (field.indexOf(".") == -1) {
        return row[field];
      } else {
        let arr = field.split(".");
        if (arr.length == 2) {
          return row[arr[0]][arr[1]];
        } else if (arr.length == 3) {
          return row[arr[0]][arr[1]][arr[2]];
        }
      }
    },
    query() {
      this.startPosition = 0;
      this.pageNum = 1;
      this.getTable();
    },
    getHead() {
      if (this.tableDatas.tableConfig) {
        let tableKey;
        if (this.tableDatas.head) {
          tableKey = this.tableDatas.head.params;
        } else {
          tableKey = this.tableDatas.body.head;
        }
        this.$http
          .GET("/wms/Menu/tableHeadPage", {
            tableKey: tableKey,
          })
          .then((data) => {
            for (let i = data.data.detailList.length - 1; i >= 0; i--) {
              if (data.data.detailList[i].hideTag == "1") {
                if (data.data.detailList[i].format) {
                  data.data.detailList[i].format = eval(
                    `({${data.data.detailList[i].format}})`
                  );
                }
              } else if (data.data.detailList[i].hideTag == "0") {
                data.data.detailList.splice(i, 1);
              }
              if (
                data.data.detailList[i] &&
                data.data.detailList[i].sumTag == "1"
              ) {
                this.summary = true;
              }
            }
            this.tableHead = data.data.detailList;
            this.tableHead.forEach(item => {
              this.$set(item, 'show', true)
              if(this.tableDatas.fixed){   //固定列
                for(let val in this.tableDatas.fixed){
                  if(item.field == val){
                    this.$set(item, 'fixed', true)
                  }
                }
              }

              if(this.tableDatas.width){   //宽度
                for(let val in this.tableDatas.width){
                  if(item.field == val){
                    this.$set(item, 'width', this.tableDatas.width[val])
                  }
                }
              }
              
            })
            
            this.$emit("update:tableHead", this.tableHead);
            this.$emit("callBackHead", "callBackHead");
            if(this.tableDatas.tableCol && this.tableDatas.tableCol == true){
              this.getColTableColumns();
            }
            
          });
      } else {
        this.tableHead = this.tableDatas.head;
        this.tableHead.forEach(item => {
          this.$set(item, 'show', true)
        })
        this.$emit("update:tableHead", this.tableHead);
        //
        if (this.tableDatas.sumTag) {
          this.summary = true;
        }
      }
    },
    getTable() {
      // this.handleShow = this.tableDatas.handleShow;
      // this.loadingTable = true
      if(this.tableDatas.tableData==undefined){
         this.tableData=[]
      }
      if(this.tableDatas.exportSign != undefined ){
        this.exportSign = this.tableDatas.exportSign
      }else{
        this.exportSign = true
      }
      if (this.tableDatas.paging) {
        this.tableDatas.body.params.startPosition = this.startPosition;
        this.tableDatas.body.params.pageNo = this.pageNum;
        this.tableDatas.body.params.page = this.pageNum;
        this.tableDatas.body.params.maxResult = this.maxResult;
        this.pagingShow = true;
      } else {
        this.pagingShow = false;
      }
      // this.tableDatas.loadFlag  true:刚进页面不调接口，false：调接口
      if (this.tableDatas.tableData || this.tableDatas.loadFlag == true) {
        this.tableData = this.tableDatas.tableData;
        this.total = this.tableDatas.total;
        this.constTableData = this.tableDatas.tableData;
      } else {
        this.$http[this.tableDatas.body.type](
          this.tableDatas.body.url,
          this.tableDatas.body.params
        ).then((data) => {
          // 增加表格伸缩详情
          if(this.tableDatas.detailItem || this.tableDatas.detailTable){
            for (let index = 0; index < data.data.rows.length; index++) {
              this.$set(data.data.rows[index],"detail",{});
            }
          }
          // this.loadingTable = false
          // TODO 后续改动 判断不对
            this.$emit("update:data", data);
          if (data.data.rows && data.data.rows == null) {
            this.total = 0;
            this.tableData = [];
            this.$emit("update:tableData", this.tableData);
            this.constTableData = data.data.rows;
            return;
          }
          //新增排序
          var that = this;
          let sort = [];
          //获取排序字段
          for (let index = 0; index < that.tableHead.length; index++) {
            if (
              that.tableHead[index].sortTag != null &&
              that.tableHead[index].sortTag != 0
            ) {
              sort.push(that.tableHead[index]);
            }
          }
          //如果只有一个排序字段
          if (sort.length == 1) {
            let indexName = sort[0].field;
            data.data.rows.sort(function (y, x) {
              if (typeof x[indexName] == "string") {
                return x[indexName].localeCompare(y[indexName]);
              }
              if (typeof x[indexName] == "number") {
                return x[indexName] - y[indexName];
              }
            });
          }
          //如果有二个排序字段
          if (sort.length == 2) {
            let fistindex;
            let lowindex;
            for (let index = 0; index < sort.length; index++) {
              if (sort[index].sortTag == 1) {
                fistindex = sort[index].field;
              }
              if (sort[index].sortTag == 2) {
                lowindex = sort[index].field;
              }
            }

            data.data.rows.sort(function (y, x) {
              if (x[fistindex] == y[fistindex]) {
                if (typeof x[lowindex] == "string") {
                  return x[lowindex].localeCompare(y[lowindex]);
                }
                if (typeof x[lowindex] == "number") {
                  return x[lowindex] - y[lowindex];
                }
              }

              if (typeof x[fistindex] == "string") {
                return x[fistindex].localeCompare(y[fistindex]);
              }
              if (typeof x[fistindex] == "number") {
                return x[fistindex] - y[fistindex];
              }
            });
          }

          if (this.tableDatas.paging) {
            if (data.data.rows) {
              this.tableData = data.data.rows;
              this.$emit("update:tableData", this.tableData);
              this.total = data.data.total;
              this.$emit("update:total", this.total);
              this.constTableData = data.data.rows;
            } else {
              this.tableData = data.data.page.rows;
              this.$emit("update:tableData", this.tableData);
              this.total = data.data.page.total;
              this.$emit("update:total", this.total);
              this.constTableData = data.data.page.rows;
              if (data.data.totalCostMoney || data.data.totalCostMoney === 0) {
                this.moneyShow = true;
                this.totalCostMoney = data.data.totalCostMoney;
                this.$emit("update:totalCostMoney", this.totalCostMoney);
              } else if(data.data.totalMoney || data.data.totalMoney === 0){
                this.moneyShow = true;
                this.totalCostMoney = data.data.totalMoney;
                this.$emit("update:totalCostMoney", this.totalMoney);
              } else {
                this.moneyShow = false;
              }
            }
          } else {
            if (data.data.rows) {
              this.tableData = data.data.rows;
              this.$emit("update:tableData", this.tableData);
              this.constTableData = data.data.rows;
            } else if(data.data.result) {
              this.tableData = data.data.result;
              this.$emit("update:tableData", this.tableData);
              this.constTableData = data.data.result;
            } else if(data.data.page && data.data.page.rows){
               this.tableData = data.data.page.rows;
              this.$emit("update:tableData", this.tableData);
              this.total = data.data.page.total;
              this.$emit("update:total", this.total);
              this.constTableData = data.data.page.rows;
              if (data.data.totalCostMoney || data.data.totalCostMoney === 0) {
                this.moneyShow = true;
                this.totalCostMoney = data.data.totalCostMoney;
                this.$emit("update:totalCostMoney", this.totalCostMoney);
              } else if (data.data.totalMoney || data.data.totalMoney === 0){
                this.moneyShow = true;
                this.totalCostMoney = data.data.totalMoney;
                this.$emit("update:totalCostMoney", this.totalMoney);
              } else {
                this.moneyShow = false;
              }
            }
            else{
              this.tableData = data.data;
              this.$emit("update:tableData", this.tableData);
              this.constTableData = data.data;
            }
          }
          //新增合并行
          if(this.tableDatas.spanMethod) this.getRowSpan()
          if (this.tableDatas.multiKey) {
            this.tableDatas.selectList.forEach((rep) => {
              this.tableData.forEach((res) => {
                this.$nextTick(() => {
                  if (
                    rep[this.tableDatas.multiKey] ==
                    res[this.tableDatas.multiKey]
                  ) {
                    this.$refs.topictable.toggleRowSelection(res, true);
                  }
                });
              });
            });
          }
          this.$emit("update:tableData", this.tableData);
          if (this.tableDatas.body.head == 'STORE_MOVEGOODS_PAGE') {
            this.tableData = this.tableData.filter((item, index) => {
              return item.goodsTypeName != "消耗品"
            })
            this.total = this.tableData.length;
          }
        }).catch(() => {
          // this.loadingTable = false
        });
      }
    },
    editClick(row) {
      if (this.tableDatas.checkFlow && row.stat != "0" && row.stat != "3") {
        this.$message({
          type: "warning",
          message: "非新建和驳回单据不允许修改!",
        });
        return;
      } else {
        this.$emit("editClick", row);
      }
    },
    checkedClick(row) {
      this.$emit("checkedClick", row);
    },
    sxClick(row) {
      this.$emit("sxClick", row);
    },
    resetClick(row) {
      this.$emit("resetClick", row);
    },
    tovoidClick(row) {
      if (this.tableDatas.checkFlow && row.stat != "0" && row.stat != "3") {
        this.$message({
          type: "warning",
          message: "非新建和驳回单据不允许作废!",
        });
        return;
      } else {
        this.$emit("tovoidClick", row);
      }
    },
    tovoidClick1(row) {
      if (this.tableDatas.checkFlow && row.stat != "0" && row.stat != "3") {
        this.$message({
          type: "warning",
          message: "非新建和驳回单据不允许作废!",
        });
        return;
      } else {
        this.$confirm("确定作废?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$http[this.tableDatas.tovoid.type](
            this.tableDatas.tovoid.url,
            this.tableDatas.tovoid.params(row)
          ).then((data) => {
            if (data.code == 200) {
              this.$message({
                type: "success",
                message: "作废成功!",
              });
              this.getTable();
            }
          });
        });
      }
    },
    detailClick(row) {
      this.$emit("detailClick", row);
    },
   
    //商品分享操作
    promotion(row){
      this.$emit("promotion", row);
    },
    //商品编辑SKU
    editSkuFun(row){

      this.$emit("editSku", row);
    },
    restockClick(row) {
      this.$emit("restockClick", row);
    },
    // 退回
    goBackClick(row) {
      this.$emit("goBackClick", row);
    },
    goStopClick(row) {
      this.$emit("goStopClick", row);
    },
    sendGoodClick(row) {
      this.$emit("sendGoodClick", row);
    },
    confirmClick(row) {
      this.$emit("confirmClick", row);
    },
    forbiddenClick(row) {
      this.$emit("forbiddenClick", row);
    },
    forbiddenClick1(row) {
      this.$emit("forbiddenClick1", row);
    },
    definedClick(row) {
      this.$emit("definedClick", row);
    },
    defined2Click(row) {
      this.$emit("defined2Click", row);
    },
    defined3Click(row) {
      this.$emit("defined3Click", row);
    },
    defined4Click(row) {
      this.$emit("defined4Click", row);
    },
    defined5Click(row) {
      this.$emit("defined5Click", row);
    },
    delClick(row) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http[this.tableDatas.delete.type](
          this.tableDatas.delete.url,
          this.tableDatas.delete.params(row)
        ).then((data) => {
          if (data.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getTable();
          }
        });
      });
    },
    delClick2(row) {
      this.$emit("delClick2", row);
    },
    upClick(row) {
      this.$emit("upClick", row);
    },
    lowClick(row) {
      this.$emit("lowClick", row);
    },
    subGoodsClick(row) {
      this.$emit("subGoodsClick", row);
    },
    redGoodsClick(row) {
      this.$emit("redGoodsClick", row);
    },
    imgSrc(id) {
      return `/manager/fileserver/file/download?id=${id}`;
    },
    // 通过弹窗获取数据
    getwpgldata(val) {
      this.tableData = val.data.rows;
      this.total = val.data.total;
      if (this.tableData == null) {
        this.tableData = [];
        this.total = 0;
      }
      this.$emit("update:tableData", this.tableData);
    },
    tmpGetData(cellback) {
      this.$nextTick(() => {
        cellback(this.tableData);
      })
    },
  },
  watch: {
    //全局过滤
    search: function (val) {
      let timer = null;
      var tmpdata = JSON.parse(JSON.stringify(this.constTableData));
      clearTimeout(timer)
       timer = setTimeout(() => {
        this.tableData = tmpdata.filter((item) => {
          for (let index = 0; index < this.tableHead.length; index++) {
            if (
              item[this.tableHead[index].field] != null &&
              String(item[this.tableHead[index].field])
                .toUpperCase()
                .indexOf(val.toUpperCase()) != -1
            ) {
              return true;
            }
          }
          return false;
        });
      }, 1000);
    },  
    'tableDatas.tableData':{
      handler(newVal){
        this.tableDatas.tableData = newVal
        this.getTable();
        this.getHead();
        
      },
      deep:true,
      immediate:true,
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
 .content{
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.el-checkbox{
  width: 84px;
}
</style>
<style>
.demo-table-expand {
  margin-left: 10px !important;
  font-size: 0!important;
}
.demo-table-expand label {
  width: 180px !important;
  color: #99a9bf !important;
}
.demo-table-expand .el-form-item {
  margin-right: 0 !important;
  margin-bottom: 0 !important;
  width: 50% !important;
}
</style>